using Microsoft.EntityFrameworkCore;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Infrastructure.Persistence;

using UwinEducation.Shared.Models;

namespace UwinEducation.Infrastructure.Repositories
{
    public class CourseRepository : Repository<Course, Guid>, ICourseRepository
    {
        public CourseRepository(ApplicationDbContext context) : base(context)
        {
        }

        public async Task<PagedResult<Course>> GetPagedListAsync(CoursePageRequest pageRequest)
        {
            var query = _context.Courses.AsQueryable();

            //if (!string.IsNullOrEmpty(pageRequest.Search))
            //{
            //    query = query.Where(c => c.Name.Contains(pageRequest.Search) ||
            //                           c.Code.Contains(pageRequest.Search));
            //}
            if (!string.IsNullOrEmpty(pageRequest.Code))
                query = query.Where(c => c.Code.Contains(pageRequest.Code));
            if (!string.IsNullOrEmpty(pageRequest.Name))
                query = query.Where(c => c.Name.Contains(pageRequest.Name));
            if (!string.IsNullOrEmpty(pageRequest.Remarks))
                query = query.Where(c => c.Remarks.Contains(pageRequest.Remarks));

            //升序，Code，转换成int后排序  code='00000001' 前面的0不参与排序
            query = query.OrderBy(c => c.Code.PadLeft(8, '0'));

            var total = await query.CountAsync();
            var items = await query
                .Skip((pageRequest.PageIndex - 1) * pageRequest.PageSize)
                .Take(pageRequest.PageSize)
                .ToListAsync();

            return new PagedResult<Course>
            {
                Total = total,
                Items = items
            };
        }

        public async Task<Course> GetDetailsByIdAsync(Guid id)
        {
            return await _context.Courses
                .FirstOrDefaultAsync(c => c.Id == id);
        }

        public async Task<bool> ExistsByCodeAsync(string code, Guid? excludeId = null)
        {
            return await _context.Courses
                .Where(c => c.Code == code && (!excludeId.HasValue || c.Id != excludeId.Value))
                .AnyAsync();
        }
    }
}